package com.topc.ucenter.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.topc.base.model.UserAuthDto;
import com.topc.ucenter.mapper.CourseInfoMapper;
import com.topc.ucenter.mapper.CourseUserMidMapper;
import com.topc.ucenter.mapper.RoleInfoMapper;
import com.topc.ucenter.mapper.UserInfoMapper;
import com.topc.ucenter.model.dto.AuthParamsDto;
import com.topc.ucenter.model.po.UserInfo;
import com.topc.ucenter.service.IAuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private ApplicationContext applicationContext;

    // 这里是处理 username 参数 以及填装权限和认证登录的地方
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        AuthParamsDto authParamsDto = null;
        try {
            authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        } catch (Exception e) {
            throw new RuntimeException("请求认证参数不符合要求");
        }
        String authType = authParamsDto.getAuthType();
        String beanName = authType+"_auth_service";
        IAuthService authService =  applicationContext.getBean(beanName, IAuthService.class);
        UserAuthDto userAuthDto = authService.execute(authParamsDto);
        System.out.println(userAuthDto);
        UserDetails userPrincipal = getUserPrincipal(userAuthDto, authParamsDto.getPassword());
        return userPrincipal;
    }

    public UserDetails getUserPrincipal(UserAuthDto authDto,String password){
        return User.withUsername(JSON.toJSONString(authDto)).roles(authDto.getRole())
                .password(password).authorities(authDto.getMenuCodes()).build();
    }
}
